#-*-coding:utf-8-*-
import web
import os
from model import *

urls = (
    '/', 'hello',#查看接口
	'/login', 'login',#登录
	'/register', 'register',#注册
	'/getLocation','getLocation',#获取签到经纬度
	'/selectCourse','selectCourse',#学生选课
	'/check', 'check',#签到
	'/addCourse', 'addCourse',#教师加课
	'/deleteCourse', 'deleteCourse',#教师删除课程
	'/openCheck', 'openCheck',#教师发起签到
	'/closeCheck', 'closeCheck',#教师关闭签到
	'/sQuery', 'sQuery',#学生查看自己有什么课程
	'/tQuery', 'tQuery',#教师查看自己有什么课程
	'/cQuery', 'cQuery',#学生查看自己某个课程签到情况
	'/cQueryAll', 'cQueryAll'#教师查看自己某个课程签到情况
)

#测试
class hello:
	def GET(self):
		#return urls
		con = Connect()
		query = 'select name from Students where sid= "13354001"'
		ok = Exec(con, query)
		return len(ok);
		data = ''
		for i in ok:
			for j in i:
				data += str(j) + ' '
		return data
#登录，post用户类型（uType，"teacher"/"student"）+用户号（uid）+密码（pw）+设备号(did)，return student_ok / teacher_ok / uType wrong / fault
class login:
	def GET(self):
		return 'uType("teacher"/"student"), uid(string) and pw(string) required, return "ok"'
	def POST(self):
		para = web.input()
		uType = para['uType']
		uid = para['uid']
		pw = para['pw']
		did = para['did']
		con = Connect()
		if uType=='student': # 学生登录
			query='select password from Students where sid="'+str(uid)+'"'
			ok = Exec(con,query)
			if len(ok)==0:
				return 'fault' # 学生不存在
			elif ok[0][0]==pw:
				query = 'select did from Students where sid="'+str(uid)+'"'
				ok = Exec(con,query)
				if ok[0][0] != str(did):
					return 'device_different' # 设备号对不上
				else:
					return 'student_ok' # 登录成功
			else:
				return 'fault' # 密码错误
		elif uType=='teacher': # 教师登录
			query='select password from Teachers where tid="'+str(uid)+'"'
			ok = Exec(con,query)
			if len(ok)==0:
				return 'fault'
			elif ok[0][0]==pw:
				return 'teacher_ok'
			else:
				return 'fault'
		else:
			return 'fault'
#注册，post用户类型（uType，"teacher"/"student"）+用户号（uid）+名字（name）+密码（pw）+设备号（did），return ok / uType wrong / used
class register:
	def GET(self):
		return 'uType("teacher"/"student") ,uid(string), name(string) and pw(string) required, return "ok"'
	def POST(self):
		para = web.input()
		uType = str(para['uType'])
		uid = str(para['uid'])
		name = str(para['name'])
		pw = str(para['pw'])
		did = str(para['did'])
		con = Connect()
		if uType=='teacher': #教师注册
			query = 'select * from Teachers where tid ="'+uid+'"'
			ok = Exec(con,query)
			if len(ok)>0:
				return 'used'
			query = 'insert into Teachers(tid, name, password) values("'+uid+'","'+name+'","'+pw+'")'
			ok = Exec(con,query)
			return 'ok'
		elif uType=='student': #学生注册
			query = 'select * from Students where sid ="'+uid+'"'
			ok = Exec(con,query)
			if len(ok)>0:
				return 'used'
			query = 'insert into Students(sid, name, password, did) values("'+uid+'","'+name+'","'+pw+'","'+did+'")'
			ok = Exec(con,query)
			return 'ok'
		else:
			return 'uType wrong'
#获取签到经纬度，post 学号(cid)，return 经纬度（空格分隔）
class getLocation:
	def GET(self):
		return 'cid(int) required, return longitude and latitude'
	def POST(self):
		para = web.input()
		cid = str(para['cid'])
		con = Connect()
		query = 'select tid from Courses where cid='+cid # 获得教师号
		ok = Exec(con,query)
		tid = str(ok[0][0])
		query = 'select longitude, latitude from Teachers where tid="'+tid+'"'
		ok = Exec(con,query)
		data = 'ok '
		for i in ok:
			for j in i:
				data += str(j) + ' '
		return data
#学生选课，post学号（sid）+课程号（cid），return ok / course_repeat
class selectCourse:
	def GET(self):
		return 'sid(string), cid(int) required, return ok'
	def POST(self):
		para = web.input()
		sid = str(para['sid'])
		cid = str(para['cid'])
		con = Connect()
		query = 'select * from Course'+cid+' where uid="'+sid+'"'
		ok = Exec(con,query)
		if len(ok)>0:
			return 'course_repeat'
		query = 'insert into Course'+cid+'(uid) values("'+sid+'")'
		ok = Exec(con,query)
		query = 'insert into Studies values("'+sid+'", '+cid+')'
		ok = Exec(con,query)
		data = 'ok'
		return data
#签到，post第几节课（which）+学号（sid）+课程号（cid），return ok
class check:
	def GET(self):
		return 'which(int, 第几次课), sid(string), cid(int) required, return "ok"'
	def POST(self):
		para = web.input()
		which = para['which']# 第几节课
		sid = para['sid']
		cid = para['cid']
		con = Connect()
		query = 'select c'+str(which)+' from Course'+str(cid)+' where uid="0"'
		status = Exec(con,query)
		#return status[0][0]
		if status[0][0]==1:#正在签到
			query = 'select c'+str(which)+' from Course'+str(cid)+' where uid="'+str(sid)+'"'
			ok = Exec(con,query)
			if ok[0][0]==1:
				return 'checked'
			query = 'update Course'+str(cid)+' set c'+str(which)+'="1" where uid="'+str(sid)+'"'
			ok = Exec(con,query)
			return 'ok'
		elif status[0][0]==0:
			return 'not started'
		elif status[0][0]==-1:
			return 'ended'
		else:
			return 'no'
#教师加课，post 教师号（tid）+课程名（cname），return ok	
class addCourse:
	def GET(self):
		return 'tid(string), cname(string) required, return "ok"'
	def POST(self):
		para = web.input()
		tid = para['tid']
		cname = para['cname']
		con = Connect()
		query = 'insert into Courses values(null, "'+str(tid)+'", "'+str(cname)+'")' # 插入到Courses
		ok = Exec(con,query)
		query = 'select MAX(cid) from Courses' # 找cid
		ok = Exec(con,query)
		cid = ok[0][0]
		#建表
		query = 'CREATE TABLE IF NOT EXISTS Course'+str(cid)+'('
		query = query + 'uid char(11) NOT NULL,'
		for i in range(1,20):
			query = query+'c'+str(i)+' int(11) NOT NULL DEFAULT 0,'
		query = query + 'PRIMARY KEY (uid)'
		query = query + ') ENGINE=MyISAM DEFAULT CHARSET=utf8;'
		#return query
		ok = Exec(con,query)
		query = 'insert into Course'+str(cid)+'(uid) values("0")'#初始值
		ok = Exec(con,query)
		return 'ok'
#教师发起签到，post 哪节课（which）+课程号（cid）+（经度）longitude+（纬度）latitude，return ok
class openCheck:
	def GET(self):
		return 'which(int, course time), cid(int) required, return "ok"'
	def POST(self):
		para = web.input()
		which = str(para['which'])
		cid = str(para['cid'])
		longitude = str(para['longitude'])
		latitude = str(para['latitude'])
		con = Connect()
		query = 'select tid from Courses where cid='+cid # 获得教师号
		ok = Exec(con,query)
		tid = str(ok[0][0])
		query = 'update Teachers set longitude='+longitude+', latitude='+latitude+' where tid="'+tid+'"' # 修改教师地理位置
		ok = Exec(con,query)
		query = 'update Course'+str(cid)+' set c'+str(which)+'="1" where uid="0"' # 修改为正在签到
		#return query
		ok = Exec(con,query)
		return 'openCheck'
#教师关闭签到，post 哪节课（which）+课程号（cid），return ok
class closeCheck:
	def GET(self):
		return 'which(int, course time), cid(int) required, return "ok"'
	def POST(self):
		para = web.input()
		which = str(para['which'])
		cid = str(para['cid'])
		con = Connect()
		query = 'update Course'+str(cid)+' set c'+str(which)+'="-1" where uid="0"'
		#return query
		ok = Exec(con,query)
		return 'closeCheck'
#学生查看自己有什么课程，post 学号（sid），return n个{课程名+课程号+教师名}（以@分隔）/ no_data
class sQuery:
	def GET(self):
		return 'sid(string) required, return {cname cid tname}'
	def POST(self):
		para = web.input()
		sid = str(para['sid'])
		con = Connect()
		query = 'select cid from Studies where sid="'+sid+'"'
		#return query
		cids = Exec(con,query)
		#return cids[0][0]
		if len(cids)==0:
			return 'no_data'
		data = ''
		for index in range(len(cids)):
			query = 'select cname, tid from Courses where cid='+str(cids[index][0])
			#return query
			cname_tid = Exec(con,query)
			query = 'select name from Teachers where tid="'+str(cname_tid[0][1])+'"'
			tname = Exec(con,query)
			
			data += str(cname_tid[0][0]) + '@'	#cname
			data += str(cids[index][0]) + '@'	#cid
			data += str(tname[0][0]) + '@'		#tname
		return data[:-1];
#教师查看自己有什么课程，post 教师号（tid），return n个{课程名+课程号}（以@分隔） / no_data
class tQuery:
	def GET(self):
		return 'tid(string) required, return {cid cname}'
	def POST(self):
		para = web.input()
		tid = str(para['tid'])
		con = Connect()
		query = 'select cname, cid from Courses where tid="'+tid+'"'
		#return query
		cname_cid = Exec(con,query)
		if len(cname_cid)==0:
			return 'no_data'
		data = ''
		#return cname_cid
		for i in cname_cid:
			for j in i:
				data += str(j) + '@'	#cname and cid
			query = 'select name from Teachers where tid="'+tid+'"'
			tname = Exec(con,query)
			data += str(tname[0][0]) + '@'	#tname
		return data[:-1];
#学生查看自己某个课程签到情况，post 学号（sid）+ 课程号（cid），return 1个{0 + 20个整数}（-1：结束，0：未开始，1：正在签到） + 1个{学号 + 20个整数}（0：没签，1：签了）（以@分隔）
class cQuery:
	def GET(self):
		return 'sid(string), cid(int) required, return 0 and 20 integers(check status), sid and 20 integers(self status)'
	def POST(self):
		para = web.input()
		sid = str(para['sid'])
		cid = str(para['cid'])
		con = Connect()
		query = 'select * from Course'+cid+' where uid="0" or uid="'+sid+'"'
		line = Exec(con,query)
		if len(line)==0:
			return ''
		data = ''
		for i in line:
			for j in i:
				data += str(j) + '@'
		return data[:-1];
#教师查看自己某个课程签到情况，post 课程号（cid），return 1个{"0" + 20个整数}（-1：结束，0：未开始，1：正在签到） + n个{学号 + 20个整数}（0：没签，1：签了）（以@分隔）
class cQueryAll:
	def GET(self):
		return 'cid(int) required, return {sid + 20 integers}'
	def POST(self):
		para = web.input()
		cid = str(para['cid'])
		con = Connect()
		query = 'select * from Course'+cid
		rows = Exec(con, query)
		if len(rows)==0:
			return ''
		#return rows
		data = ''
		for row in rows:
			for col in row:
				data += str(col) + '@'
		return data[:-1];
		
app = web.application(urls, globals()).wsgifunc()
application = sae.create_wsgi_app(app)

